<?php

namespace App\Utils\WeChat;
use EasyWeChat\Kernel\Exceptions\BadRequestException;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\RuntimeException;
use EasyWeChat\OfficialAccount\Application;
use Illuminate\Http\RedirectResponse;
use Illuminate\Routing\Redirector;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

/**
 * 公众号
 */
class RbhOfficialWebWeChat implements WeChat
{
    private string $appId = 'wx287f4dd4fedce32a';
    private string $appSecret = '6d639e18f71659ea6f4f9ed43a005b49';

    private Application $app;

    /**
     * 构造实例
     * @throws InvalidArgumentException
     */
    public function __construct()
    {
        $config = [
            'app_id' => $this->appId,
            'secret' => $this->appSecret,
            'token' => 'fCoJz5PV1ek2Lrh',
            'oauth' => [
                'scopes'   => ['snsapi_base'],
                'redirect_url' => '/examples/oauth_callback.php',
            ],
        ];
        $this->app = new Application($config);
    }

    /**
     * 自定义回复
     * @return void
     * @throws InvalidArgumentException
     * @throws BadRequestException
     * @throws RuntimeException
     * @throws \ReflectionException
     * @throws \Throwable
     */
    public function messageResponse(): void
    {
        $server = $this->app->getServer();
        $server->addEventListener('subscribe', function($message, \Closure $next) {
            return '感谢您关注绒博汇!';
        });
        $server->serve();
    }

    /**
     * oauth回调
     * @return \Closure|\Illuminate\Contracts\Foundation\Application|\Illuminate\Foundation\Application|RedirectResponse|Redirector|mixed|object|null
     * @throws InvalidArgumentException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function oauth(): mixed
    {
        $oauth = $this->app->getOauth();
        if (!session()->get('openid')) {
            $redirectUrl = $oauth->redirect('callback_url');
            return redirect($redirectUrl);
        } else
            return session()->get('openid');
    }

    /**
     * 回调
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Foundation\Application|RedirectResponse|Redirector
     */
    public function callback(): \Illuminate\Foundation\Application|Redirector|RedirectResponse|\Illuminate\Contracts\Foundation\Application
    {
        try {
            $oauth = $this->app->getOauth();
            $user = $oauth->userFromCode($_REQUEST['code']);
            $userData = $user->toArray();
            session()->put('openid', $userData['id']);
            session()->save();
            return redirect('/api/wechat/oauth');
        } catch (\Exception $e) {
            return redirect('/404?message=' . $e->getMessage());
        }
    }

    public function getUserOpenId($code)
    {
        // TODO: Implement getUserOpenId() method.
    }

    public function getUserMobile($code)
    {
        // TODO: Implement getUserMobile() method.
    }
}
